/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package light;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import javax.swing.JApplet;

/**
 *
 * @author Khorn
 */
public class MainWorkSpace extends Canvas implements Runnable {

    private ArrayList<Ray> listRays;
    private boolean dopF = false;
    private int index;
    private int indexR;
    private boolean rotate;
    public static Image fon;
    private int mouse_x = 0;
    private int mouse_y = 0;
    private boolean intersection = false;
    private int permitted_x = 0;
    private int permitted_y = 0;
    private int shiftX = 0;
    private int shiftY = 0;
    private Thread thread; 
               
    private ArrayList<Sprite> stage;        //  список объектов уровня

    public void start(int i) {
        //заполнение уровня в зависимости от его порядкового номера
        Light.successDialog.currentLevel = i;
        stage = new ArrayList();
        switch (i){
            // уровень 1
            case 0:
                stage.add(getSprite("picks/q1.jpg", 0, 0, 1));
                stage.add(getSprite("picks/q1.jpg", 100, 100, 2));
                stage.add(getSprite("picks/q1.jpg", 200, 200, 1));
                break;
            //уровень 2
            case 1:
                stage.add(getSprite("picks/q1.jpg", 100, 300, 1));
                break;
            default:
                Light.workspace.stop();
                Light.workspace.setVisible(false);
                Light.utilityPanel.setVisible(false);
                Light.successDialog.setVisible(false);
                Light.frame.remove(Light.workspace);
                Light.frame.remove(Light.utilityPanel);
                Light.frame.remove(Light.successDialog);
                Light.frame.add(Light.credits);
                Light.credits.setVisible(true);
                Light.frame.pack();
                Light.frame.setLocationRelativeTo(null);
                break;
        }
        thread = new Thread(this);
// массив лучей необходимо убрать и заменить их объектом-источником
        listRays = new ArrayList();
        thread.start();
    }

    public void stop() {
        thread.interrupt();
    }

    @Override
    public void run() {
            long lastTime = System.currentTimeMillis();
            long delta;

            init();

            while (!thread.isInterrupted()) {
                delta = System.currentTimeMillis() - lastTime;
                lastTime = System.currentTimeMillis();
                render();
                update(delta);
            }
//            System.out.print("thread is finished\n"); 
    }

    private void init() {
        Mouser mm = new Mouser();
        addMouseMotionListener(mm);
        addMouseListener(mm);
        Color c = new Color(120, 0, 0);
        Ray r = new Ray(0, 400, 100, 300, c);
        listRays.add(r);
        fon = getImage("picks/fon.jpg");

    }

    public void render() {
        BufferStrategy bs = getBufferStrategy();
        if (bs == null) {
            createBufferStrategy(2);
            requestFocus();
            return;
        }

        Graphics g = bs.getDrawGraphics();
        g.setColor(Color.black);
        g.fillRect(0, 0, getWidth(), getHeight());
        g.drawImage(fon, 0, 0, this);
        for (int i = 0; i < stage.size(); i++) {
            stage.get(i).draw(g);
        }
        listRays.get(0).draw(g);
        g.dispose();
        bs.show();
    }

    public void update(long delta) {
        if (stage.get(index).getFlag() == true) {
            stage.get(index).setX(mouse_x - shiftX);
            stage.get(index).setY(mouse_y - shiftY);
        }

        intersection = false;
        for (int j = 0; j < stage.size(); j++) {
            if ((j != index) && (stage.get(index).intersect(stage.get(j)))) {
                intersection = true;
            }
        }
        if (intersection == false) {
            permitted_x = mouse_x - shiftX;
            permitted_y = mouse_y - shiftY;
        }
        for (int j = 0; j < stage.size(); j++) {
            Point p = new Point(listRays.get(0).getX2(), listRays.get(0).getY2());
            Point pn = stage.get(j).lineIntersect(listRays.get(0));
            //                if(Math.sqrt(Math.pow(p.x, 2)+Math.pow(p.y, 2)) > Math.sqrt(Math.pow(pn.x, 2)+Math.pow(pn.y, 2))){
            if (p != pn) {
                listRays.get(0).setX2(pn.x);
                listRays.get(0).setY2(pn.y);
            } else {
                listRays.get(0).setX2(600);
                listRays.get(0).setY2(600);
            }
        }

    }

    public Sprite getSprite(String path, int x, int y, int t) {
        BufferedImage sourceImage = null;

        try {
            URL url = this.getClass().getClassLoader().getResource(path);
            sourceImage = ImageIO.read(url);
        } catch (IOException e) {
            e.printStackTrace();
        }

        Sprite sprite = new Sprite(Toolkit.getDefaultToolkit().createImage(sourceImage.getSource()), x, y, t);
        return sprite;
    }

    public Image getImage(String path) {
        BufferedImage sourceImage = null;
        try {
            URL url = this.getClass().getClassLoader().getResource(path);
            sourceImage = ImageIO.read(url);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sourceImage;
    }

    private class Mouser extends JApplet implements MouseListener, MouseMotionListener {

        @Override
        public void mouseClicked(MouseEvent e) {
        }

        @Override
        public void mousePressed(MouseEvent e) {
            for (int i = 0; i < stage.size(); i++) {
                if (dopF == false) {
                    if ((stage.get(i).getT() == 1) && (e.getX() > stage.get(i).getX()) && (e.getX() < (stage.get(i).getX() + stage.get(i).getWidth()))
                            && ((e.getY() > stage.get(i).getY()) && (e.getY() < (stage.get(i).getY() + stage.get(i).getHeight())))) {
                        stage.get(i).setFlag(true);
                        index = i;
                        dopF = true;
                        shiftX = e.getX() - stage.get(i).getX();
                        shiftY = e.getY() - stage.get(i).getY();
                        intersection = false;
                    }
                    if ((stage.get(i).getT() == 2) && (e.getX() > stage.get(i).getX()) && (e.getX() < (stage.get(i).getX() + stage.get(i).getWidth()))
                            && ((e.getY() > stage.get(i).getY()) && (e.getY() < (stage.get(i).getY() + stage.get(i).getHeight())))) {
                        indexR = i;
                        rotate = true;
                    }
                }
            }
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            dopF = false;
            stage.get(index).setFlag(false);
            index = 0;
            index = 0;
            if (intersection == true) {
                stage.get(index).setX(permitted_x);
                stage.get(index).setY(permitted_y);
            }
            rotate = false;
        }

        @Override
        public void mouseEntered(MouseEvent e) {
        }

        @Override
        public void mouseExited(MouseEvent e) {
        }

        @Override
        public void mouseDragged(MouseEvent e) {

            mouse_x = e.getX();
            mouse_y = e.getY();

            intersection = false;

            for (int j = 0; j < stage.size(); j++) {
                if ((j != index) && (stage.get(index).intersect(stage.get(j)))) {
                    intersection = true;
                }

            }
            if (intersection == false) {
                permitted_x = mouse_x - shiftX;
                permitted_y = mouse_y - shiftY;
            }
            if (rotate) {
                double angle = stage.get(indexR).getAngle();
                if (mouse_y != stage.get(indexR).getYc()) {
                    angle += Math.atan((mouse_x - stage.get(indexR).getXc()) / (mouse_y - stage.get(indexR).getYc()));
                    stage.get(indexR).setAngle(angle);
                }
            }

        }

        @Override
        public void mouseMoved(MouseEvent e) {
        }

    }

}
